package com.jpcc.vw.onlineRadio.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.Display;
import android.view.WindowManager;


public class HorizontalScrollTextView extends android.support.v7.widget.AppCompatTextView {
    private float textLength = 0f;// 文本长度
    private float viewWidth = 0f;//文本控件的长度
    private float step = -20f;// 文本的横坐标
    private float y = 0f;// 文本的纵坐标
    public boolean isStarting = false;// 是否开始滚动
    private Paint paint = null;
    private String text = "";// 文本内容

    private int max = 470;

    public HorizontalScrollTextView(Context context) {
        super(context);
    }

    public HorizontalScrollTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HorizontalScrollTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    public void setMax(int max) {
        this.max = max;
    }

    public void init(WindowManager windowManager) {
        paint = getPaint();
        //设置滚动字体颜色
        paint.setColor(max == 470 ? Color.WHITE : Color.parseColor("#74767e"));
        text = getText().toString();
        textLength = paint.measureText(text);
        viewWidth = getWidth();
        if (viewWidth == 0) {
            if (windowManager != null) {
                Display display = windowManager.getDefaultDisplay();
                viewWidth = display.getWidth();
            }
        }
        y = getTextSize() + getPaddingTop();
    }

    //开启滚动
    public void startScroll() {
        isStarting = true;
        invalidate();
    }

    //停止滚动
    public void stopScroll() {
        isStarting = false;
        invalidate();
    }

    @Override
    public void onDraw(Canvas canvas) {
        canvas.drawText(text, -step, y, paint);
        if (!isStarting) {
            return;
        }
        // 2.0为文字的滚动速度
        step += 0.5;
        //判断是否滚动结束
//        if (step > textLength - 480) {
//            step = -20;
//        }
        if (step == textLength) {
            step = -max;
        }
        if (textLength < (max - 20)) {
            step = 0;
        }
        invalidate();
    }


}
